﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class EnemyBehavior : MonoBehaviour
{
    [SerializeField] private Transform target;

    [SerializeField] public float approachSpeed;
    public float speedmodifier;

    [SerializeField] public float enemyHealth = 100;

    private Slider healthBar;
    private ResourceManager resM;
    
    // Start is called before the first frame update
    void Start()
    {
        target = GameObject.Find("VitualBase").transform;
        this.gameObject.GetComponentInChildren<Canvas>().worldCamera = Camera.main;
        healthBar = this.gameObject.GetComponentInChildren<Slider>();
        resM = GameObject.Find("GameManager").GetComponent<ResourceManager>();
    }

    // Update is called once per frame
    void Update()
    {
        EnemyApproachesTarget();
        healthControl();
        healtbarcontrol();
        //enemyHealth -= 0.1f;
        //speedmodifier = 1;
        this.gameObject.transform.GetChild(0).transform.LookAt(Camera.main.transform.position);
    }

    void EnemyApproachesTarget()
    {
        Vector3 approachVector = target.position - this.gameObject.transform.position;
        this.gameObject.transform.position += approachVector.normalized * approachSpeed * Time.deltaTime * speedmodifier;
    }

    void healthControl()
    {
        if (enemyHealth < 0)
        {
            resM.dirtSource += 5;
            Destroy(this.gameObject);
        }
    }

    private void healtbarcontrol()
    {
        healthBar.value = enemyHealth / 100;
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Base")
        {
            SceneManager.LoadScene(0);
            Debug.Log("lol");
        }
    }

    private void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "Base")
        {
            SceneManager.LoadScene(0);
            Debug.Log("lol");
        }
    }
}
